<template>
  <div class="treeDataBox" style="margin-top: 20px">
    <el-table
      :data="nodeData"
      default-expand-all
      style="width: 100%"
      border
      row-key="uid"
      stripe
      size="small"
      :tree-props="{
        children: 'children',
        hasChildren: 'hasChildren',
      }"
    >
      <el-table-column prop="targetName" label="目标名称"></el-table-column>
      <el-table-column prop="originalName" label="原始名称"></el-table-column>
      <el-table-column prop="paramType" label="参数类型"></el-table-column>
      <el-table-column prop="required" label="是否必填">
        <template slot-scope="scope">
          <el-tag
              v-if="scope.row.pid != null"
              size="small"
              :type="scope.row.required ? 'success' : 'danger'"
              disable-transitions
              >{{ scope.row.required ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="example" label="示例值"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-tooltip content="添加子节点" placement="top">
            <el-button
              v-if="scope.row.paramType == 'Object' || scope.row.paramType == 'Array' || scope.row.pid == null"
              size="mini"
              @click="appendChild(scope.row)"
              circle
              type="primary"
              icon="el-icon-plus"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              v-if="scope.row.pid != undefined && scope.row.pid != null"
              size="mini"
              circle
              type="danger"
              icon="el-icon-minus"
              @click="remove(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button
              v-if="scope.row.pid != undefined && scope.row.pid != null"
              size="mini"
              circle
              type="info"
              icon="el-icon-edit"
              @click="edit(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-dialog
        :title="dialogTitle"
        width="480px"
        style="text-align: left"
        :visible.sync="isShow"
        :close-on-click-modal="false"
        :before-close="beforClose"
        destroy-on-close
        append-to-body
      >
        <el-form
          ref="tableForm"
          :model="tableForm"
          label-width="100px"
          size="small"
          :rules="tableFormRules"
        >
          <el-form-item label="目标名称" prop="targetName">
            <el-input
              v-model="tableForm.targetName"
              @input="onInput"
            ></el-input>
          </el-form-item>
          <el-form-item label="原始名称" prop="originalName">
            <el-input
              v-model="tableForm.originalName"
              @input="onInput"
            ></el-input>
          </el-form-item>
          <el-form-item label="参数类型" prop="paramType">
            <el-select
              size="small"
              v-model="tableForm.paramType"
              filterable
              placeholder="请选择参数类型"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="it in paramTypeOptions"
                :key="it"
                :label="it.label"
                :value="it.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否必填">
            <el-switch
            size = 'mini'
            v-model="tableForm.required"
            active-color="#13ce66">
            </el-switch>
          </el-form-item>
          <el-form-item label="示例值">
            <el-input v-model="tableForm.example" @input="onInput"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-if="!editMode" @click="addNode"
              >创建</el-button
            >
            <el-button type="primary" v-if="editMode" @click="updateNode"
              >更新</el-button
            >
            <el-button @click="beforClose">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import ajax from "~/api/ajax";
export default {
  props: {
    value: Array,
    rootName: String,
    needRootSwitch: Boolean,
  },
  data() {
    var checkTargetName = (rule, value, callback) => {
      let isRepeat = this.validateRepeat(
        this.editMode ? this.curRow.pid : this.curRow.uid,
        value,
        "targetName"
      );
      if (isRepeat) {
        callback(new Error("目标名称重复"));
      } else {
        callback();
      }
    };
    var checkOriginalName = (rule, value, callback) => {
      let isRepeat = this.validateRepeat(
        this.editMode ? this.curRow.pid : this.curRow.uid,
        value,
        "originalName"
      );
      if (isRepeat) {
        callback(new Error("原始名称重复"));
      } else {
        callback();
      }
    };

    return {
      dialogTitle: "添加节点",
      curRow: null,
      isShow: false,
      editMode: false,
      paramTypeOptions: [],
      tableForm: {
        targetName: null,
        originalName: null,
        example: null,
        required: false,
        paramType: null
      },
      tableFormRules: {
        targetName: [
          { required: true, message: "目标名称不能为空" },
          { validator: checkTargetName, trigger: "blur" },
        ],
        originalName: [
          { required: true, message: "原始名称不能为空" },
          { validator: checkOriginalName, trigger: "blur" },
        ],
        paramType: [
          { required: true, message: "参数类型不能为空" },
        ],
      },
      nodeData: [
        this.value
      ],
    };
  },
  mounted() {
    let that = this;
    ajax.get("/apiManage/paramTypes").then((rs) => {
      that.paramTypeOptions = rs.data;
    });
  },
  methods: {
    onInput() {
      this.$forceUpdate();
    },
    getTableNodeData() {
      return this.nodeData[0].children;
    },
    validateRepeat(rowId, value, field) {
      let node = this.findTableNode(rowId);
      console.log('当前行id：' + rowId + '找到的节点：' + JSON.stringify(node));
      if (node == null || node.children == null || node.children.length == 0) {
        return false;
      }

      var [...arr] = node.children;
      if (this.editMode) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].uid === this.curRow.uid) {
            arr.splice(i, 1);
          }
        }
      }

      for (var i = 0; i < arr.length; i++) {
        if (arr[i][field] === value) {
          return true;
        }
      }
      return false;
    },
    getUuid() {
      var s = [];
      var hexDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";
      let uuid = s.join("");
      return uuid;
    },
    addNode() {
      this.$refs["tableForm"].validate((valid) => {
        if (valid) {
          const uid = this.getUuid();
          const node = {
            pid: this.curRow.uid,
            uid: uid,
            targetName: this.tableForm.targetName,
            originalName: this.tableForm.originalName,
            example: this.tableForm.example,
            paramType: this.tableForm.paramType,
            required: this.tableForm.required,
            isRoot: false,
            children: [],
          };
          console.log('创建节点，父id: ' + this.curRow.uid + ' id: ' + uid);

          this.curRow.children.push(node);
          this.isShow = false;
          this.curRow = null;
          this.tableForm = {};
        }
      });
    },
    updateNode() {
      this.$refs["tableForm"].validate((valid) => {
        if (valid) {
          this.curRow.targetName = this.tableForm.targetName;
          this.curRow.originalName = this.tableForm.originalName;
          this.curRow.example = this.tableForm.example;
          this.curRow.paramType = this.tableForm.paramType,
          this.curRow.required = this.tableForm.required,
          this.tableForm = {};
          this.isShow = false;
          this.editMode = false;
        }
      });
    },
    appendChild(row) {
      this.isShow = true;
      this.curRow = row;
      this.dialogTitle = "添加节点";
    },
    edit(row) {
      this.tableForm = {
        targetName: row.targetName,
        originalName: row.originalName,
        example: row.example,
        paramType: row.paramType,
        required: row.required,
        isRoot: row.isRoot,
      };
      this.curRow = row;
      this.editMode = true;
      this.isShow = true;
      this.dialogTitle = "更新节点";
    },
    beforClose() {
      this.isShow = false;
      this.editMode = false;
      this.tableForm = {};
    },
    removeNode(row) {
      const pid = row.pid;
      const uid = row.uid;
      console.log("父id：" + pid + " id: " + row.uid);
      var parentNode = this.findTableNode(pid);

      // 在父节点的孩子中找到该节点下标进行移除
      if (parentNode != null) {
        let arr = parentNode.children;
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].uid === uid) {
            arr.splice(i, 1);
            break;
          }
        }
      }
    },
    remove(row) {
      if (row.children != null && row.children.length != 0) {
        this.$confirm("当前删除节点包含子节点！确定删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
        }).then(() => {
          this.removeNode(row);
        });
      } else {
        this.removeNode(row);
      }
    },
    iterateTableNode(tableData, arr) {
      // console.log(JSON.stringify(tableData));
      if (tableData == null) {
        return;
      }
      arr.push(tableData);
      for (var i = 0; i < tableData.children.length; i++) {
        this.iterateTableNode(tableData.children[i], arr);
      }
    },
    findTableNode(uid) {
      let tempArr = [];
      this.iterateTableNode(this.nodeData[0], tempArr);
      let node = null;
      for (var i = 0; i < tempArr.length; i++) {
        if (tempArr[i].uid === uid) {
          node = tempArr[i];
          break;
        }
      }
      return node;
    },
  },
};
</script>